﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MillerApp.DataAccess.MillerDB;
using MillerApp.DataContract.MillerDB;
using MillerApp.UserControls;
using MillerApp.UserControls.Enums;
using MillerApp.Stock.Maintain;

namespace MillerApp.Stock
{
    public partial class StockInfoQueryForm : SubFormBase
    {
        public StockInfoQueryForm()
        {
            InitializeComponent();
        }

        //默认排序字段和顺次 [默认是按照证券代码升序排列]
        string column = "seccode";
        SortDirection direction = SortDirection.ASC;

        //当前用户
        UserEntity currentUser = null;
        List<StockqtreadinfosEntity> tempNotesList = null;

        private void StockInfoQueryForm_Load(object sender, EventArgs e)
        {
            //获取当前用户
            currentUser = Common.Common.GetCurrentUser(this);
            //dataGridView1.ShowCellToolTips = true;
            this.dataGridView1.AutoGenerateColumns = false;
            this.queryActions1.PagerControl = this.dataPagerControl1;
            this.queryActions1.OnQueryingData += new QueryingDataEventHandler(queryActions1_OnQueryingData);
            this.queryActions1.GetConditions += new GetStringDelegate(queryActions1_GetConditions);
            this.queryActions1.GetSortExpression += new GetSortExpression(queryActions1_GetSortExpression);
            dataGridView1.ColumnHeaderMouseClick += delegate(object sender2, DataGridViewCellMouseEventArgs e2)
            {
                column = this.queryActions1.CurrentSortColumn;
                direction = this.queryActions1.CurrentSortDirection;
                string columnName = dataGridView1.Columns[e2.ColumnIndex].Name;
                if (columnName.IndexOf("GRD_EXP") >= 0)
                {
                    return;
                }
                ////retail_EX//allflow_EX//inflowmain_EX
                if (columnName == "inflowmain_EX")
                {
                    columnName = "(inflowmain-outflowmain)";
                }
                if (columnName == "retail_EX")
                {
                    columnName = "(inflowretail-outflowretail)";
                }
                if (columnName == "allflow_EX")
                {
                    columnName = "(inflowmain-outflowmain+inflowmain-outflowmain)";
                }
                //if (columnName == "secshortname")
                //{
                //    columnName = "seccode";
                //}

                if (columnName == column)
                {
                    direction = direction == SortDirection.ASC ? SortDirection.DESC : SortDirection.ASC;
                }
                else
                {
                    column = columnName;
                }
                this.queryActions1.OnQueryData();
            };
        }

        SortExpression queryActions1_GetSortExpression()
        {
            SortExpression exp = new SortExpression();
            exp.SortColumn = column;
            exp.SortDirection = direction;
            return exp;
        }

        string queryActions1_GetConditions()
        {
            string conditions = string.Empty;
            if (string.IsNullOrEmpty(txtTypeName.Text) == false)
            {
                //MainForm mainForm = this.ParentForm as MainForm;
                //List<SecurityEntity> securities = mainForm.Securities;
                //var d=from b in securities
                //      where b.secshortname.IndexOf(txtTypeName.Text)
                conditions += " and (secCode like '%" + txtTypeName.Text + "%' or secshortname like '%" + txtTypeName.Text + "%' or upper(pysx) like '%" + txtTypeName.Text.ToUpper() + "%')";
            }
            if (string.IsNullOrEmpty(this.dpkerStart.Text) == false)
            {
                conditions += " and tradeday>= '" + dpkerStart.Value.Date.ToString("yyyy-MM-dd") + "'";
            }
            if (string.IsNullOrEmpty(this.dpkerEnd.Text) == false)
            {
                conditions += " and tradeday<= '" + dpkerEnd.Value.Date.ToString("yyyy-MM-dd") + "'";
            }
            return conditions;
        }

        void queryActions1_OnQueryingData(string conditions, string sortExpression, int pageIndex, int pageSize)
        {
            //查询
            int recordCount = 0;
            List<StockquotationsEntity> list = StockquotationsManager.GetStockquotationssByCond(conditions, sortExpression, pageIndex, pageSize, out recordCount);

            
            //获取备注信息
            if (pageIndex == 0)
            {
                string queryConditions = " and userid='" + currentUser.userid + "'";
                if (string.IsNullOrEmpty(this.dpkerStart.Text) == false)
                {
                    queryConditions += " and tradeday>= '" + dpkerStart.Value.Date.ToString("yyyy-MM-dd") + "'";
                }
                if (string.IsNullOrEmpty(this.dpkerEnd.Text) == false)
                {
                    queryConditions += " and tradeday<= '" + dpkerEnd.Value.Date.ToString("yyyy-MM-dd") + "'";
                }
                int recordCount2 = 0;
                tempNotesList = StockqtreadinfosManager.GetStockqtreadinfossByCond(queryConditions, string.Empty, 0, int.MaxValue, out recordCount2);
            }
            //获取证券简称
            //MainForm mainForm = this.ParentForm as MainForm;
            //List<SecurityEntity> securities = mainForm.Securities;
            //foreach (var item in list)
            //{
            //    var a = from b in securities
            //            where b.seccode.Trim().ToLower() == item.seccode.Trim().ToLower()
            //            select b;
            //    if (a != null)
            //    {
            //        item.secshortname = a.FirstOrDefault<SecurityEntity>().secshortname;
            //    }
            //}
            this.dataGridView1.DataSource = list;
            this.queryActions1.RecorderCount = recordCount;
            SetDataGridStyle(dataGridView1);
        }

        private void SetDataGridStyle(DataGridView gridView)
        {
            for (int i = 0; i < gridView.Rows.Count; i++)
            {
                //1. 设置字体颜色
                #region 设置字体颜色
                gridView.Rows[i].Cells["GRD_EXP_ROWNO"].Value = (i + 1).ToString();
                List<int> setRedCells = new List<int>();
                object obj = gridView.Rows[i].DataBoundItem;
                if (obj == null)
                {
                    continue;
                }
                StockquotationsEntity dataItem = obj as StockquotationsEntity;
                if (dataItem == null)
                {
                    continue;
                }
                if (dataItem.mainflow > 0)
                {
                    SetCellForeColor(gridView, i, (int)ColumnIndex.MainFlow, Color.Red);
                }
                else
                {
                    SetCellForeColor(gridView, i, (int)ColumnIndex.MainFlow, Color.Green);
                }
                if (dataItem.retailflow > 0)
                {
                    SetCellForeColor(gridView, i, (int)ColumnIndex.RetailFlow, Color.Red);
                }
                else
                {
                    SetCellForeColor(gridView, i, (int)ColumnIndex.RetailFlow, Color.Green);
                }
                if (dataItem.allflow > 0)
                {
                    SetCellForeColor(gridView, i, (int)ColumnIndex.AllFlow, Color.Red);
                }
                else
                {
                    SetCellForeColor(gridView, i, (int)ColumnIndex.AllFlow, Color.Green);
                }
                if (dataItem.changeratio > 0)
                {
                    SetCellForeColor(gridView, i, (int)ColumnIndex.ChangeRatio, Color.Red);
                }
                else
                {
                    SetCellForeColor(gridView, i, (int)ColumnIndex.ChangeRatio, Color.Green);
                }
                if (dataItem.todayclosingprice - dataItem.yesterdayclosingprice > 0)
                {
                    SetCellForeColor(gridView, i, (int)ColumnIndex.Price, Color.Red);
                }
                else
                {
                    SetCellForeColor(gridView, i, (int)ColumnIndex.Price, Color.Green);
                }
                #endregion 设置字体颜色
                //2. 设置其他样式
                if (dataItem.changeratio.HasValue && (System.Math.Abs(dataItem.changeratio.Value) >= (decimal)0.09))
                {
                    DataGridViewCellStyle style = gridView.Rows[i].Cells[(int)ColumnIndex.ChangeRatio].Style;
                    style.BackColor = Color.Yellow;
                    style.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));

                    //gridView.Rows[i].Cells[(int)ColumnIndex.ChangeRatio].ToolTipText = "我买进";
                }
                //3.设置备注
                var a = from b in tempNotesList
                        where b.seccode.Trim() == dataItem.seccode.Trim() && b.tradeday == dataItem.tradeday
                        select b;
                if (a != null && a.Count<StockqtreadinfosEntity>() > 0)
                {
                    StockqtreadinfosEntity currentEntity = a.FirstOrDefault<StockqtreadinfosEntity>();
                    DataGridViewCellStyle style = gridView.Rows[i].Cells[(int)ColumnIndex.TradeDay].Style;
                    style.BackColor = Color.Yellow;
                    gridView.Rows[i].Cells[(int)ColumnIndex.TradeDay].ToolTipText = currentEntity.notes;
                    //style.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
                }
            }
        }

        private void SetCellForeColor(DataGridView gridView, int row, int cell, Color color)
        {
            gridView.Rows[row].Cells[cell].Style.ForeColor = color;
        }

        private enum ColumnIndex
        {
            SecCode=2,
            MainFlow = 4,
            RetailFlow = 5,
            AllFlow = 6,
            ChangeRatio = 7,
            Price = 8,
            AddNotes = 1,
            TradeDay=1,
        }


        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0)
            {
                return;
            }
            object obj = dataGridView1.Rows[e.RowIndex].DataBoundItem;
            if (obj == null)
            {
                return;
            }
            StockquotationsEntity dataItem = obj as StockquotationsEntity;
            if (dataItem == null)
            {
                return;
            }
            //双击查询一个月（默认按日期排序）
            if (e.ColumnIndex == (int)ColumnIndex.SecCode)
            {
                //查询1个月
                string secCode = dataItem.seccode;
                this.txtTypeName.Text = secCode;
                this.dpkerEnd.Value = DateTime.Now.Date;
                this.dpkerStart.Value = DateTime.Now.Date.AddMonths(-1);

                //排序
                column = "tradeday";
                direction = SortDirection.ASC;
                this.queryActions1.OnQueryData();
            }

            else if(e.ColumnIndex == (int)ColumnIndex.TradeDay)
            {
                //双击查询一个月（默认按日期排序）
                //增加备注
                string secCode = dataItem.seccode;
                string secShortName = dataItem.secshortname;
                DateTime tradeDay = dataItem.tradeday.Value;
                string userid = currentUser.userid;
                string notes = string.Empty;

                StockqtReadinfoMaintain form = new StockqtReadinfoMaintain();
                StockqtreadinfosEntity currentEntity = null;
                var a = from b in tempNotesList
                        where b.seccode.Trim() == dataItem.seccode.Trim() && b.tradeday == dataItem.tradeday
                        select b;
                if (a != null && a.Count<StockqtreadinfosEntity>() > 0)
                {
                    form.ActionTypeCode = ActionType.Modify;
                    currentEntity = a.FirstOrDefault<StockqtreadinfosEntity>();
                }
                else
                {
                    string conditions = " and userid='" + userid + "' and seccode='" + secCode + "' and tradeday='" + tradeDay.ToString("yyyy-MM-dd") + "'";
                    int recordCount;
                    List<StockqtreadinfosEntity> list = StockqtreadinfosManager.GetStockqtreadinfossByCond(conditions, string.Empty, 0, int.MaxValue, out recordCount);
                    if (list != null && list.Count > 0)
                    {
                        currentEntity = list[0];
                    }
                }
                if (currentEntity == null)
                {
                    currentEntity = new StockqtreadinfosEntity();
                    currentEntity.seccode = secCode;
                    currentEntity.tradeday = tradeDay;
                    currentEntity.userid = userid;
                    form.ActionTypeCode = ActionType.AddNew;
                }
                currentEntity.secshortname = dataItem.secshortname;
                form.Entity = currentEntity;
                form.ShowDialog();
            }
        }

    }
}
